package cn.xianshu.config;

import cn.xianshu.handle.MyAuthenticationFailureHandler;
import cn.xianshu.handle.MyAuthenticationSuccessHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {



    //配置认证管理器，授权模式为“poassword”时会用到
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }




    /**
     * 密码加密器：
     * NoOpPasswordEncoder.getInstance():不加密
     * BCryptPasswordEncoder(); 加密
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {

        // return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder(); // 加密
    }


    /**
     * 授权规则配置
     * HttpSecurity : 对url的权限配置
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http.authorizeRequests() // 授权配置
                .antMatchers("/login/user", "/login/saveLoginAndMeal","/login/save").permitAll() // 登录路径放行
                .anyRequest().authenticated() // 其他路径都要认证之后才能访问
                .and().formLogin() // 允许表单登录
                .successHandler(new MyAuthenticationSuccessHandler()) // 认证成功结果处理器
                .failureHandler(new MyAuthenticationFailureHandler()) // 认证失败处理器
                .and().logout().permitAll() // 登出路径放行 /logout
                .and().csrf().disable(); // 关闭跨域伪造检查
    }
}
